(function(){
    angular.module('app').controller("newActiveCtrl",function($scope,$stateParams,proxy){
        var activeId=$stateParams.id;
        var accountType = $stateParams.type;  //区别代理商和广告主
        var date= new Date();
        $scope.obj={
            'start':date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日",
            'end':date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日",
            'znode':[],
            'spaceIdArr' :[],
            'spaceObj':{},
            'appID':$stateParams.appID,
            'dataObj':{
                "industry": "" ,        //行业分类
                'frequencyUnit':'day',  //频次限制单位，默认天
                'dayBudget':'0' ,       //日预算，默认不限制
                'totalBudget':'0' ,     //总预算，默认不限制
                'industryName':''       //行业分类的名称
            },
            'name':'新建活动',
            'frequencyType':'天'
        };
        $scope.checkAll = ['1'];
        $scope.checkDay = ["1",'2'];
        $scope.radios = 2;
        $scope.select = [
            {
                name:"天"
            },
            {
                name:"小时"
            }
        ];
        $scope.firstType = '请选择';
        $scope.secondType = '请选择';
        $scope.searchVal = "";
        $scope.module = ['value'];
        $scope.timeLimit = true;
        $scope.startLimit = false;
        //获取行业
        proxy.proxy({
            url: STATIC_URL.domian+'/dsp/industry/type',
            data: {
            },
            success: function(res){
                $scope.firstList = res.data;
            }
        });
        $scope.firstCall = function(res){
            $scope.obj.dataObj.industryName='';
            $scope.obj.dataObj.industry='';
            $scope.secondType='请选择';
            $scope.secondList = res.subType;
            $scope.obj.dataObj.industryName =res.name;
        };
        $scope.secondCall = function(res){
            if( $scope.obj.dataObj.industryName.split(',')[0]){
                $scope.obj.dataObj.industryName =  $scope.obj.dataObj.industryName.split(',')[0]
            }
            $scope.obj.dataObj.industry = res.id;
            $scope.obj.dataObj.industryName +=','+res.name;
        }
        chooseTime();//选择时间段
        if($scope.obj.appID=='0'){ //新建
            $scope.obj.name='新建活动';

        }else if($scope.obj.appID!='0'){ //编辑
            $scope.obj.name='编辑活动';
            proxy.proxy({
                url: STATIC_URL.domian+'/dsp/activity',
                data: {
                    "id":$scope.obj.appID
                },
                success: function(res){
                    console.log(res);
                    // 获得列表
                    $scope.obj.dataObj = res.data;
                    $scope.obj.frequencyType = res.data.frequencyUnit=='hour'?'小时':'天';
                    $scope.firstType = res.data.industryName.split(',')[0];
                    $scope.secondType = res.data.industryName.split(',')[1];
                   
                    if($scope.obj.dataObj.totalBudget && $scope.obj.dataObj.totalBudget=='0.00'){
                        $scope.checkAll=['1']
                    }else{
                        $scope.checkAll=[]

                    }
                    if($scope.obj.dataObj.dayBudget && $scope.obj.dataObj.dayBudget=='0.00'){
                        $scope.checkDay=['2']
                    }else{
                        $scope.checkDay=[]

                    }

                    //恢复开始时间，结束时间 开始时间不可以编辑
                    $scope.obj.start =ymd($scope.obj.dataObj.startTime.split(' ')[0]);
                    $scope.startLimit = true;
                    //$scope.obj.end = $scope.obj.dataObj.endTime==''?date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日":ymd($scope.obj.dataObj.endTime);
                    $scope.timeLimit = $scope.obj.dataObj.endTime==''?true:false;
                    $scope.module =  $scope.obj.dataObj.endTime==''?['value']:[];
                    $scope.obj.end = $scope.obj.dataObj.endTime==''?'':ymd($scope.obj.dataObj.endTime);
                }
            })
        }
        //时间限制
        $scope.checkTimeback = function(item){
            $scope.timeLimit = item;
        };
        //选择频次限制的单位
        $scope.daySelect = function(item){
            $scope.obj.dataObj.frequencyUnit = (item.name=='小时'?'hour':'day');
        };

        //保存新建活动
        $scope.saveActive = function(type, orderType){
            $scope.obj.dataObj.startTime = changeData($('#dpd1').text())+' ' +'00:00:00';
            $scope.obj.dataObj.endTime = changeData($('#dpd2').text())+' ' +'23:59:59';
            if( $scope.timeLimit){
                $scope.obj.dataObj.endTime='NULL';
            }
            //输入判断
            if(!$scope.obj.dataObj.name ||$scope.obj.dataObj.name==''){ //活动名称
                layer.msg('活动名称不能为空哦');
                return;
            }
            //if(!$scope.obj.dataObj.frequency ||$scope.obj.dataObj.frequency==''){ //频次
            //    layer.msg('频次控制不能为空哦');
            //    return;
            //}
            if(!$scope.obj.dataObj.industry || $scope.obj.dataObj.industry==''){
                layer.msg('行业还没选哦');
                return;
            }
            if($scope.obj.appID=='0'){
                var url = '/dsp/activity/add';
            }else if($scope.obj.appID!='0'){
                var url = '/dsp/activity/modify';
            }
            proxy.proxy({
                url: STATIC_URL.domian+url,
                data: {
                    data:$scope.obj.dataObj
                },
                success: function(res){
                    // 获得列表
                    if (type) {
                        layer.closeAll();
                        var activeName = $scope.obj.dataObj.name;
                        localStorage.step = 1;
                        window.location.href = "#/agent/"+accountType+'/'+ activeId +"/delivery/newOrder/"+ orderType +"//"+ res.data;
                    } else {
                        window.location.href='./agentIndex.html#/agent/'+accountType+'/'+activeId+'/delivery/active';
                    }
                    //http://localhost:63342/code/agentIndex.html#/agent/3/delivery1/active
                    //http://localhost:63342/code/agentIndex.html#/agent/3/delivery/active
                }
            })
        };
        //保存并创建活动弹窗
        $scope.saveAngOrder = function () {
            //输入判断
            if(!$scope.obj.dataObj.name ||$scope.obj.dataObj.name==''){ //活动名称
                layer.msg('活动名称不能为空哦');
                return;
            }
            //if(!$scope.obj.dataObj.frequency ||$scope.obj.dataObj.frequency==''){ //频次
            //    layer.msg('频次控制不能为空哦');
            //    return;
            //}
            if(!$scope.obj.dataObj.industry || $scope.obj.dataObj.industry==''){
                layer.msg('行业还没选哦');
                return;
            }

            layer.open({
                type: 1,
                title: "新建广告订单",
                skin: "layer-style",
                area: ['660px', '380px'], //宽高
                content: $(".orderType")
            });
        };
        //跳转订单
        $scope.addOrder = function (orderType) {
            $scope.saveActive('order', orderType);
        };
        //每日预算
        $scope.dayCall = function(flag){
            if(flag){
                $scope.obj.dataObj.dayBudget = '0';
            }
        };
        //总预算
        $scope.allCall = function(flag){
            if(flag){
                $scope.obj.dataObj.totalBudget = '0';
            }
        };
    })
})();

function chooseTime(){
    //订单起始时间与结束时间
    $('#demo-3').fdatepicker();
    var nowTemp = new Date();
    var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
    var checkin = $('#dpd1').fdatepicker({

        onRender: function (date) {
            return date.valueOf() < now.valueOf() ? 'disabled' : '';
        }


    }).on('changeDate', function (ev) {
        var newDate = new Date(ev.date);
        var sleTime = newDate.getFullYear()+"年"+(newDate.getMonth()+1)+"月"+(newDate.getDate())+"日";
        console.log(sleTime);

        //sTime = newDate.getFullYear()+"-"+(newDate.getMonth()+1)+"-"+(newDate.getDate());
        $("#dpd1").text(sleTime);
        if (ev.date.valueOf() > checkout.date.valueOf()) {
            newDate.setDate(newDate.getDate() + 1);
            checkout.update(newDate);
        }
        checkin.hide();
        $('#dpd2')[0].focus();
    }).data('datepicker');
    var checkout = $('#dpd2').fdatepicker({
        onRender: function (date) {
            return date.valueOf() < checkin.date.valueOf() ? 'disabled' : '';
        }
    }).on('changeDate', function (ev) {
        var newDate = new Date(ev.date)
        var sleTime = newDate.getFullYear()+"年"+(newDate.getMonth()+1)+"月"+(newDate.getDate())+"日";
        //eTime = newDate.getFullYear()+"-"+(newDate.getMonth()+1)+"-"+(newDate.getDate());
        $("#dpd2").text(sleTime);
        checkout.hide();
    }).data('datepicker');
};

//处理时间段
function changeData(data){
    var arr =data.replace('年','-').replace('月','-').replace('日','').replace(/\s/g,'').split('-');
    for(var i = 0;i<arr.length;i++){
        if(arr[i]<10){
            arr[i]='0'+arr[i];
        }
    }
    var newDate = arr.join('-');
    return newDate;
};